package com.amqr.mediaplayer.activity;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.amqr.mediaplayer.R;
import com.amqr.mediaplayer.VideoUtils;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {


    private EditText et_path;
    private Button bt_play, bt_replay, bt_pause, bt_stop;
    private SurfaceView sv;

    private SeekBar sb;
    private MediaPlayer mediaPlayer;
    private int currentPosition;
    private Boolean mIsplaying;

    private TextView mTvCurrTime;
    private TextView mTvAllTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sv = (SurfaceView) findViewById(R.id.sv);
        et_path = (EditText) findViewById(R.id.et_path);
        bt_play = (Button) findViewById(R.id.bt_play);
        bt_replay = (Button) findViewById(R.id.bt_replay);
        bt_pause = (Button) findViewById(R.id.bt_pause);
        bt_stop = (Button) findViewById(R.id.bt_stop);
        sb = (SeekBar) findViewById(R.id.sb);
        mTvCurrTime = (TextView) findViewById(R.id.mTvCurrTime);
        mTvAllTime = (TextView) findViewById(R.id.mTvAllTime);

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

        sv.getHolder().addCallback(new SurfaceHolder.Callback() {

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                System.out.println("holder被销毁了");

                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    currentPosition = mediaPlayer.getCurrentPosition();
                    stop();
                }
            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                System.out.println("holder被创建了");
                if (currentPosition > 0) {
                    play();
                }

            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format,
                                       int width, int height) {
                System.out.println("holder的大小变化了");
            }
        });






        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {
                mediaPlayer.start();
                final int max = mediaPlayer.getDuration();

                mTvAllTime.setText(VideoUtils.formatTime(max));


                sb.setMax(max);
                mediaPlayer.seekTo(currentPosition);
                new Thread() {
                    public void run() {
                        mIsplaying = true;
                        while (mIsplaying) {
                            final int position = mediaPlayer.getCurrentPosition();

                            mTvCurrTime.post(new Runnable() {
                                @Override
                                public void run() {
                                    mTvCurrTime.setText(VideoUtils.formatTime(position));
                                }
                            });


                            sb.setProgress(position);
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                    };

                }.start();

            }
        });


        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int process = seekBar.getProgress();
                if(mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.seekTo(process);
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                // TODO Auto-generated method stub

            }
        });

        bt_pause.setOnClickListener(this);
        bt_play.setOnClickListener(this);
        bt_replay.setOnClickListener(this);
        bt_stop.setOnClickListener(this);




    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_play:
                play();
                break;
            case R.id.bt_replay:
                replay();
                break;
            case R.id.bt_stop:
                stop();
                break;
            case R.id.bt_pause:
                pause();
                break;
            default:
                break;
        }
    }

    /**
     * 暂停音乐
     */
    private void pause() {
        if ("继续".equals(bt_pause.getText().toString().trim())) {
            mediaPlayer.start();
            bt_pause.setText("暂停");
            return;
        }
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            bt_pause.setText("继续");
            return;
        }
    }

    /**
     * 重新播放
     */
    private void replay() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.seekTo(0);
            return;
        }
        play();
    }

    /**
     * 停止播放音乐
     */
    private void stop() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.release(); // 记得释放资源
            mediaPlayer = null;
            bt_play.setEnabled(true);
            mIsplaying = false;
        }
    }

    /**
     * 播放音乐
     */
    private void play() {
        String path = et_path.getText().toString().trim();
        try {
            /* 设置Video影片以SurfaceHolder播放 */
            mediaPlayer.setDisplay(sv.getHolder());

            mediaPlayer.setDataSource(path);
            mediaPlayer.prepareAsync(); // might take long! (for buffering, etc)
            //mediaPlayer.prepareAsync();


            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    bt_play.setEnabled(true);
                }
            });

            bt_play.setEnabled(false);
        } catch (Exception e) {
            Toast.makeText(this, "播放失败", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }



}
